import logging

from pylons import request, response, session, tmpl_context as c,url
from pylons.controllers.util import abort, redirect_to
from pylons.decorators.secure import authenticate_form

from blog.model import User,Profile,Right,Password
from blog.model import meta
from blog.model.meta import Session

from blog.lib.base import BaseController,render
from blog.lib.decorators import condition,_or
from blog.lib.helpers import flash
from blog.lib import right
#from blog.lib import user
log = logging.getLogger(__name__)

import re
emailword=re.compile('[a-zA-Z][\w]*@[\w]*.[\w]*')

class UsersController(BaseController):

    def __before__(self):
        self.user_q = Session.query(User)
        self.right_q=Session.query(Right)

    def index(self):
        # Return a rendered template
        #return render('/users.mako')
        # or, return a response
        return 'Hello World'
    
    def login(self):
        if 'username' in session : del session['username']
        return render('/user/login.mako')
    
    @authenticate_form
    def auth(self):
        log.info('This is the auth')
        username=request.POST.getone('username')
        password=request.POST.getone('password')
        user = self.user_q.filter_by(username=username).first()
        if not user:
            flash('User not exists.')
            c.UserNotExisted = True
            c.log = log
            session['username']=username
            return render('/user/errors.mako')
        elif user.password.auth(password):
            session['user']=user
            session['right']=user.right
            log.debug('%s logined' % user.id)
            flash('Welcome back, %s' % username)
            last=session['last'] if 'last' in session else '/'
            redirect_to(last)
        else :
            flash('Login Incorrect')
            return redirect_to(url('login_user'))

    def signup(self):
        return render('/user/signup.mako')
    
    @authenticate_form
    def create(self):
        username=request.POST.getone('username')
        password=request.POST.getone('password')
        email=request.POST.getone('email')
        description=request.POST.getone('description')
        sign=request.POST.getone('sign')
        right=self.right_q.filter_by(name='default').first()
        profile=Profile(description=description,sign=sign)
        user=User(username,email)
        user.set_password(password)
        user.set_right(right)
        user.set_profile(profile)
        Session.add(user)
        Session.commit()
        log.info('Create it?')
        last=session['last'] if 'last' in session else '/'
        redirect_to(last)

    def check(self):
        username=request.GET.getone('username') if 'username' in request.GET else None
        email=request.GET.getone('email') if 'email' in request.GET else None
        if username :
            user=self.user_q.filter_by(username=username).first()
            if user :
                return 'False'
            else :
                return 'True'
        if email :
            if emailword.match(email):
                return 'True'
            else :
                return 'False'

    def manage(self,uid=None):
        user=self.user_q.filter_by(id=int(uid if uid else session['user'].id)).first()
        if user.right.secret : c.SuperUser=SuperUser
        c.username=user.username
        c.email=user.email
        #c.id=user.id  #Why do I need this?
        c.sign=user.profile.sign
        c.description=user.profile.description
        return render('/user/manage.mako')

    @authenticate_form
    def modify(self,uid):
        user=user_q.filter_by(uid=uid).first()
        user.username=request.POST.getone('username')
        password=request.POST.getone('password')
        user.email=request.POST.getone('email')
        description=request.POST.getone('description')
        sign=request.POST.getone('sign')
        right=right_q.filter_by(name='default')
        password=Password(pwd=password)
        profile=Profile(description=description,sign=sign)
        user.set_password(password)
        user.set_right(right)
        user.set_profile(profile)
        return redirect_to(session['last'] if 'last' in session else '/')

    def logoff(self):
        del session['user']
        del session['right']

